import type { User } from '@/types/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { casLogin } from '@/services/user'
import { ticket } from '@/utils/Intercept'
export const useUserStore = defineStore(
  'cp-user',
  () => {
    // 用户信息
    const user = ref<User>({
      token: getToken() || '',
      flas: ''
    })
    //区分应用
    const apps = (flas: any) => {
      user.value.flas = flas
    }
    const casLogins = async () => {
      const url = window.location.href
      const tickets = ticket(url)
      const obj = ref({
        ticket: tickets || 'ST-643788-oBAlDPlHLennyd2e6UNm-cas',
        serviceUrl: 'https://yjpt.zafu.edu.cn/appsk'
      })
      const res = await casLogin(obj.value)
      user.value.token = res.data.access_token
      setToken(res.data.access_token)
      apps('so')
    } // 清空用户，退出后使用
    const delUser = () => {
      user.value.token = undefined
      removeToken()
    }
    return { user, casLogins, delUser, apps }
  },
  {
    persist: true
  }
)
